﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Text;
using System.Data;
using System.IO;
using PlugNT.Common;
using PlugNT.Custom;
using PlugNT.Cms.BLL;
using PlugNT.Cms.Core;

namespace PlugNT.Cms.Page
{
    /// <summary>
    /// 页面文件生成类
    /// </summary>
    public class PageBuilder
    {  


        #region 生成静态页用

        /// <summary>
        /// 生成聚合页
        /// </summary>
        /// <param name="html"></param>
        /// <param name="createpath"></param>
        /// <param name="tmppath"></param>
        /// <param name="clsno"></param>
        /// <returns></returns>
        public static string CreateIndexHtml(HtmlBuilder html,string createpath,string tmppath,string clsno)
        {
            string error = "";
            tmppath = tmppath.Trim();
            if (tmppath != "")
            {
                string[] arr = tmppath.Split(',');
                foreach (string templetPath in arr)
                {
                    try
                    {
                        if (templetPath.Trim() != "")
                        {
                            string tmpFileName = PlugNT.Common.Utils.GetFileName(templetPath);
                            int tmpFlag = tmpFileName.LastIndexOf(".");
                            tmpFileName = (tmpFlag > 0) ? tmpFileName.Substring(0, tmpFlag) : tmpFileName;

                            html.CreatHtmlDir = createpath;
                            html.HtmlTempletPath = templetPath;
                            html.ChannelNo = clsno;
                            html.HtmlPageName = tmpFileName;
                            html.CreateSingleHtml();
                        }
                    }
                    catch (HtmlException ex)
                    {
                        error = ex.Message;
                    }
                }
            }
            else
            {
                error = "模板中没有匹配的文件！";
            }
            return error;

        }


        /// <summary>
        /// 生成列表页
        /// </summary>
        /// <param name="html"></param>
        /// <param name="createpath"></param>
        /// <param name="tmppath"></param>
        /// <param name="clsno"></param>
        /// <returns></returns>
        public static string CreateListHtml(HtmlBuilder html,string createpath, string tmppath, string clsno)
        {
            string error = "";
            tmppath = tmppath.Trim();
            if (tmppath != "")
            {
                string[] arr = tmppath.Split(',');
                foreach (string templetPath in arr)
                {
                    try
                    {
                        if (templetPath.Trim() != "")
                        {
                            string tmpFileName = PlugNT.Common.Utils.GetFileName(templetPath);
                            int tmpFlag = tmpFileName.LastIndexOf(".");
                            tmpFileName = (tmpFlag > 0) ? tmpFileName.Substring(0, tmpFlag) : tmpFileName;

                            html.CreatHtmlDir = createpath;
                            html.HtmlTempletPath = templetPath;
                            html.ChannelNo = clsno;
                            html.HtmlPageName = tmpFileName;
                            html.CreateListHtml();
                        }
                    }
                    catch (HtmlException ex)
                    {
                        error = ex.Message;
                    }
                }
            }
            else
            {
                error = "模板中没有匹配的文件！";
            }
            return error;
        }

        /// <summary>
        /// 生成内容页
        /// </summary>
        /// <param name="html"></param>
        /// <param name="id"></param>
        /// <param name="pagename"></param>
        /// <param name="createpath"></param>
        /// <param name="tmppath"></param>
        /// <param name="clsno"></param>
        /// <returns></returns>
        public static string CreateShowHtml(HtmlBuilder html, string id,string pagename, string createpath, string tmppath, string clsno)
        {
            string error = "";
            if (!PlugNT.Common.Utils.IsNumeric(id))
            {
                error = "指定id无效！";
            }
            else
            {
                tmppath = tmppath.Trim();
                pagename = pagename.Trim();
                if (tmppath != "")
                {
                    try
                    {
                        html.CreatHtmlDir = createpath;
                        html.HtmlTempletPath = tmppath;
                        html.ChannelNo = clsno;
                        html.IdValue = int.Parse(id);
                        html.HtmlPageName = pagename;
                        html.CreateShowHtml();
                    }
                    catch (HtmlException ex)
                    {
                        error = ex.Message;
                    }
                }
                else
                {
                    error = "模板中没有匹配的文件！";
                }
            }
            return error;
        }


        /// <summary>
        /// 执行生成(动态页面)
        /// </summary>
        /// <param name="tmpDynamicPath">模板动态页路径</param>
        /// <param name="lastCreatePath">上次生成路径(如果和生成路径一样则覆盖否则删除上次生成路径)</param>
        /// <param name="createPath">生成路径(如果为空则不生成)</param>
        /// <returns></returns>
        public static bool CreateHtml(string tmpDynamicPath, string lastCreatePath, string createPath)
        {
            try
            {
                createPath = System.Web.HttpContext.Current.Server.MapPath(createPath.Trim());
                //createPath = createPath.Trim();
                if (createPath != "")
                {
                    //编码
                    Encoding ResEncoding = System.Web.HttpContext.Current.Response.ContentEncoding;
                    //调用Execute,并且获取其输出
                    StringWriter sw = new StringWriter();
                    System.Web.HttpContext.Current.Server.Execute(tmpDynamicPath, sw);
                    string content = sw.ToString();
                    //写文件夹
                    int createFlag = createPath.LastIndexOf(@"\");
                    if (createFlag > 0)
                    {
                        string dir = createPath.Substring(0, createFlag);
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                    }
                    //写进文件
                    using (FileStream fs = new FileStream(createPath, FileMode.Create, FileAccess.Write, FileShare.Write))
                    {
                        using (StreamWriter strWriter = new StreamWriter(fs, ResEncoding))
                        {
                            strWriter.Write(content);
                        }
                    }

                }
                //删除上次生成路径
                DeleteHtml(lastCreatePath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath"></param>
        public static void DeleteHtml(string filePath)
        {
            filePath = filePath.Trim();
            if (filePath != "" && File.Exists(filePath))
            {
                File.Delete(filePath);
            }
        }


        #endregion


        /// <summary>
        /// 更新静态文件
        /// </summary>
        /// <param name="type">0为全部，1为聚合页，2为列表页</param>
        /// <param name="articlePostfix"></param>
        /// <param name="dicPath"></param>
        /// <returns></returns>
        private static string CreateStaticHtml(int type, string tablePostfix, string dicPath)
        {
            DataTable dt = DataAccess.curTemplet.GetListByPostfix(tablePostfix);
            StringBuilder sb = new StringBuilder();
            
            foreach (DataRow dr in dt.Rows)
            {
                string t_createpath = dicPath + dr["createpath"].ToString().Trim();
                string indexfile = dr["indexfile"].ToString().Trim();
                string listfile = dr["listfile"].ToString().Trim();
                string clsno = dr["clsno"].ToString();
                //生成聚合页
                if (type == 0 || type == 1)
                {
                    if (indexfile != "")
                    {
                        HtmlBuilder html = new HtmlBuilder();
                        html.TablePostFix = tablePostfix;
                        string error1 = CreateIndexHtml(html, t_createpath, indexfile, clsno);
                        if (error1 != "")
                        {
                            sb.Append(error1 + "<br />");
                        }
                    }
                }
                //生成列表页
                if (type == 0 || type == 2)
                {
                    if (listfile != "")
                    {
                        HtmlBuilder html = new HtmlBuilder();
                        html.TablePostFix = tablePostfix;
                        string error2 = CreateListHtml(html, t_createpath, listfile, clsno);
                        if (error2 != "")
                        {
                            sb.Append(error2 + "<br />");
                        }
                    }
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 生成聚合页
        /// </summary>
        /// <param name="tablePostfix"></param>
        /// <returns></returns>
        public static string CreateIndexHtmls(string tablePostfix, string dicPath)
        {
            return CreateStaticHtml(1, tablePostfix, dicPath);
        }

        /// <summary>
        /// 生成列表页
        /// </summary>
        /// <param name="tablePostfix"></param>
        /// <returns></returns>
        public static string CreateListHtmls(string tablePostfix, string dicPath)
        {
            return CreateStaticHtml(2, tablePostfix, dicPath);
        }

        /// <summary>
        /// 更新次数
        /// </summary>
        public static long UpdateCount = 0;

        /// <summary>
        /// 更新静态文件
        /// </summary>
        public static void UpdatePages()
        {
            UpdateCount++;
            if (UpdateCount >= long.MaxValue)
            {
                UpdateCount = 0;
            }

            DataTable dt = new Tables().GetList();
            foreach (DataRow dr in dt.Rows)
            {
                string postfix = dr["postfix"].ToString();
                string dicpath = dr["path"].ToString().Trim();
                string t_createpath = (dicpath == "") ? "/" : "/" + dicpath + "/";
                //整站生成
                CreateStaticHtml(0, postfix, t_createpath);
            }
        }

        #region contact me
        public static string Help()
        {
            return @"mailto:549002835@qq.com";
        }
        #endregion
    }
}

